package cn.jekun.shop.app.service;

import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.EncryptUtil;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.MD5;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.RsDevice;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.bean.gen.RsUserShop;
import cn.jekun.component.core.service.gen.RsDeviceService;
import cn.jekun.component.core.service.gen.RsUserService;
import cn.jekun.component.core.service.gen.RsUserShopService;
import cn.jekun.component.core.validator.annotation.UserName;
import cn.jekun.shop.common.service.CartService;
import cn.jekun.shop.common.service.ShopBaseService;
import cn.jekun.shop.web.bean.ErpCarts;
import cn.jekun.shop.web.bean.User;

@Service(LoginService.BEAN_NAME)
public class LoginService extends ShopBaseService {
	public static final String BEAN_NAME = "cn.jekun.shop.common.service.LoginService";
	public static final String NAMESPACE = "SHOP_MEMBER_USER";

	@Resource(name=CartService.BEAN_NAME)
	CartService cartService;
	
	@Override
	public String getNamespace() {
		return NAMESPACE;
	}
	
	@Resource(name=RsUserService.BEAN_NAME)
	RsUserService rsUserService;
	
	@Resource(name=RsUserShopService.BEAN_NAME)
	RsUserShopService rsUserShopService;
	
	@Resource(name = RsDeviceService.BEAN_NAME)
	private RsDeviceService rsDeviceService;
	
	@SuppressWarnings({ "rawtypes", "unused", "unchecked" })
	public JSONObject loginApp(
			@UserName
			String userName, 
			@MD5(message="旧密码未加密")
			String password,
			@Security
			String sign,
			@Security
			String sessionId) {
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		List resultList = new ArrayList();
		Map formMap = new HashMap();
		if (StringUtils.isBlank(userName)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户名不能为空");
		}
		if (StringUtils.isBlank(password)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"密码不能为空");
		}
		password = this.versionCompatible(password);
		Map tempUserMap = new HashMap();
		// 通過userName的用户是否存在
		//SqlUtis.prepareSql(tempUserMap, "","and (b.user_name='"+userName+"' or b.mobile='"+userName+"')");
		SqlUtis.prepareSql(tempUserMap, "","and b.mobile='"+userName+"'");
		User rsUser = this.one(tempUserMap);
		if (rsUser == null) {
			SqlUtis.prepareSql(tempUserMap, "","and b.user_name='"+userName+"'");
			rsUser = this.one(tempUserMap);
		}
		
		//登录验证
		String loginSign = EncryptUtil.md5(sign + System.currentTimeMillis());//登录签名
		if (rsUser == null) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户不存在");
		} else {
			String pwd = rsUser.getPassword();
			// 密码不为空并且密码相同则将会员的信息保存到session并且登录成功，反之失败返回登录页面
			if (pwd != null && pwd.equals(password)) {
				jsonObject.put("userId", rsUser.getUserId());
				jsonObject.put("userName", rsUser.getUserName());
				jsonObject.put("mobile", rsUser.getMobile());
				jsonObject.put("loginSign", loginSign);
				Map tempRsUserMap = new HashMap();
				tempRsUserMap.put(RsUser.COL_USER_ID,rsUser.getUserId());
				RsUser tempUser = new RsUser();
				tempUser.setLoginSignApp(loginSign);
				tempUser.setLoginTime(new Date());
				tempRsUserMap.put("rsUser", tempUser);
				SqlUtis.prepareSql(tempRsUserMap, 
						SqlUtis.getSQL(tempRsUserMap, "a."+RsUser.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ));
				this.rsUserService.update(tempRsUserMap);
				Map queryMap = new HashMap();
				queryMap.put("userId", rsUser.getUserId());
				//登录成功后，合并购物车
				try {
					cartService.changeTempGoodsToUser(rsUser.getUserId(),sessionId);
					ErpCarts result = cartService.one(this.cartService.getStatementName("queryCartGoodsNum"), queryMap);
					jsonObject.put("cartNums", result.getNums()==null?"0":""+result.getNums());
				} catch (Exception e) {
					e.printStackTrace();
				}
				Map tempMap = new HashMap();
				tempMap.put(RsUser.COL_USER_ID, rsUser.getUserId());
				SqlUtis.prepareSql(tempMap, 
						SqlUtis.getSQL(tempMap, "a."+RsUser.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ));
				RsUserShop tempUserShop = rsUserShopService.one(tempMap);
				if(tempUserShop != null){
					jsonObject.put("shopId", tempUserShop.getShopId());
				}else{
					jsonObject.put("shopId", "");
				}
				return executeRerutn(jsonObject);
			} else {
				throw new BusinessException(
						Constants.ERRORS.VALIDATE_ERROR_CODE, "用户名密码错误");
			}
		}

	}
	/**
	 * 退出
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject logoutApp(String userId,String deviceId){
		JSONObject jsonObject = new JSONObject();

			if (StringUtils.isBlank(userId)) {
				throw new BusinessException(
						Constants.ERRORS.VALIDATE_ERROR_CODE, "用户编码不能为空");
			}
//			if (StringUtils.isBlank(deviceId)) {
//				throw new BusinessException(
//						Constants.ERRORS.VALIDATE_ERROR_CODE, "当前移动设备编码不能为空");
//			}
			Map tempMap = new HashMap();
			tempMap.put(RsUser.COL_USER_ID, userId);
			RsUser user = new RsUser();
			user.setLoginSignApp("");
			tempMap.put("rsUser", user);
			SqlUtis.prepareSql(tempMap, "", SqlUtis.getSQL(tempMap, "a."
					+ RsUser.COL_USER_ID, Types.VARCHAR, SqlUtis.EQ));
			int total = this.rsUserService.update(tempMap);
//			if (total != 1) {
//				throw new BusinessException(
//						Constants.ERRORS.VALIDATE_ERROR_CODE, "退出失败");
//			}
			// 当前设备非登录状态
			if(StringUtils.isNotBlank(deviceId)){
				RsDevice device = new RsDevice();
				device.setDeviceId(deviceId);
				device.setIsOnline("0");
				this.rsDeviceService.update(device);
			}
		return executeRerutn(jsonObject);
	}
	
	/**
	 *  抢红包用户登录
	 *  @param userName
	 *  @param password
	 *  @param sign
	 *  @return
	 *
	 */
	public JSONObject loginApp(@UserName String userName, @MD5(message="旧密码未加密")String password) {
		JSONObject jsonObject = new JSONObject();
		Map formMap = new HashMap();
		if (StringUtils.isBlank(userName)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户名不能为空");
		}
		if (StringUtils.isBlank(password)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"密码不能为空");
		}
		password = this.versionCompatible(password);
		Map tempUserMap = new HashMap();
		// 通過userName的用户是否存在
		//SqlUtis.prepareSql(tempUserMap, "","and (b.user_name='"+userName+"' or b.mobile='"+userName+"')");
		SqlUtis.prepareSql(tempUserMap, "","and b.mobile='"+userName+"'");
		User rsUser = this.one(tempUserMap);
		if (rsUser == null) {
			SqlUtis.prepareSql(tempUserMap, "","and b.user_name='"+userName+"'");
			rsUser = this.one(tempUserMap);
		}
		
		if (rsUser == null) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户不存在");
		} else {
			String pwd = rsUser.getPassword();
			// 密码不为空并且密码相同则将会员的信息保存到session并且登录成功，反之失败返回登录页面
			if (pwd != null && pwd.equals(password)) {
				jsonObject.put("userId", rsUser.getUserId());
				jsonObject.put("userName", rsUser.getUserName());
				jsonObject.put("mobile", rsUser.getMobile());
				return executeRerutn(jsonObject);
			} else {
				throw new BusinessException(
						Constants.ERRORS.VALIDATE_ERROR_CODE, "用户名密码错误");
			}
		}
	}
		
}
